package admin

import (
	"context"

	"server/internal/svc"
	"server/internal/types"
	"server/models"
	"server/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type SpecKeyListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSpecKeyListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SpecKeyListLogic {
	return &SpecKeyListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SpecKeyListLogic) SpecKeyList(req *types.SpecKeyListReq) (resp *types.SpecKeyListResp, err error) {
	tx := utils.Db.Model(&models.SpecKey{}).Joins("LEFT JOIN spec_template ON spec_keys.spec_template_id = spec_template.id")
	if req.Name != "" {
		tx.Where("spec_keys.name LIKE ?", "%"+req.Name+"%")
	}
	if req.SpecTemplateID != 0 {
		tx.Where("spec_keys.spec_template_id = ?", req.SpecTemplateID)
	}

	total := utils.TxCount(tx)
	if total == 0 {
		return &types.SpecKeyListResp{
			Total: total,
			List:  []types.SpecKeyListRespItem{},
		}, nil
	}
	tx = tx.Select("spec_keys.*,spec_template.name as spec_template_name").Order("spec_keys.id desc")
	datas := make([]types.SpecKeyListRespItem, 0)
	utils.TxPage(tx, req.Page, &datas)
	return &types.SpecKeyListResp{
		Total: total,
		List:  datas,
	}, nil
}
